package com.ruoyi.project.utils;

import com.alibaba.druid.support.json.JSONUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.project.push.AppPush;
import com.ruoyi.project.system.user.domain.User;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Component
public class GouldUtils {

    private static final Logger log = LoggerFactory.getLogger(GouldUtils.class);


    @Value("${gould.key}")
    private String key;
    @Value("${gould.url.query_terminal}")
    private String queryTerminalUrl;
    @Value("${gould.url.add_terminal}")
    private String addTerminalUrl;
    @Value("${gould.url.del_terminal}")
    private String delTerminalUrl;
    @Value("${gould.url.del_trace_terminal}")
    private String delTraceTerminalUrl;
    @Value("${gould.url.add_trace}")
    private String addTrace;
    @Value("${gould.url.trace_point_upload}")
    private String tracePointUpload;
    @Value("${gould.url.aroundsearch}")
    private String aroundsearch;
    @Value("${gould.url.search}")
    private String search;
    @Value("${gould.taskSid}")
    private String taskSid;
    @Value("${gould.userSid}")
    private String userSid;

    private Map<String,Object> bindMap=new HashMap<>();


    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private AppPush appPush;

    @Autowired
    private RestTemplate restTemplate;

    public void createTaskTerminal( String lat, String lng,String typeId) throws  Exception{
        List points=new LinkedList();
        Map<String,Object> pointMap=new HashMap<>();
        pointMap.put("location",lat+","+lng);
        pointMap.put("locatetime", DateUtils.getNowDate().getTime());
        points.add(pointMap);
        StringBuffer sb=new StringBuffer();
        //查询任务终端是否存在
        Map<String,String> queryMap=new HashMap<>();
        queryMap.put("key",key);
        queryMap.put("sid",taskSid);
        queryMap.put("name",typeId+"");
        String queryStr = HttpUtils.getParam(queryMap);
        String queryResult = HttpUtils.sendGet(queryTerminalUrl, queryStr);
        String tid="";
        if (StringUtils.isBlank(queryResult)){
            throw new RuntimeException("终端查询错误");
        }
        JSONObject jsonObject = new JSONObject(queryResult);
        if (jsonObject!=null && !jsonObject.isNull("data") && jsonObject.getJSONObject("data").getInt("count")!=0
                && jsonObject.getJSONObject("data").getJSONArray("results").getJSONObject(0).get("tid")!=null) {
            tid=jsonObject.getJSONObject("data").getJSONArray("results").getJSONObject(0).get("tid").toString();
        }else {
            //生成任务终端

            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            param.add("key", key);
            param.add("sid", taskSid);
            param.add("name", typeId + "");
            param.add("desc", "任务"+typeId);
            Map<String, Object> responseMessage = requestGould(param, addTerminalUrl);
            log.info("生成终端：" + JSONUtils.toJSONString(responseMessage));
            if (Integer.valueOf(responseMessage.get("errcode").toString()).intValue() != 10000) {
                throw new RuntimeException("终端生成错误:" + responseMessage.get("errdetail").toString());
            }
            tid = ((Map) responseMessage.get("data")).get("tid").toString();
        }


        //生成轨迹
        MultiValueMap<String, Object> paramTrack = new LinkedMultiValueMap<>();
        paramTrack.add("key",key);
        paramTrack.add("sid",taskSid);
        paramTrack.add("tid",tid);
        Map<String, Object> responseMessageTrack = requestGould(paramTrack, addTrace);
        log.info("生成轨迹："+JSONUtils.toJSONString(responseMessageTrack));
        if (Integer.valueOf(responseMessageTrack.get("errcode").toString()).intValue()!=10000){
            throw new RuntimeException("轨迹生成错误:"+responseMessageTrack.get("errdetail").toString());
        }

        createTrackPoint(points, tid, ((Map)responseMessageTrack.get("data")).get("trid").toString(),typeId+"");

        log.info("*****************轨迹点生成成功*******************");

        //扫描附近用户端发起任务推送
 //       BigDecimal taskDecimal = new BigDecimal(5.0);


        //查询附近终端
//        MultiValueMap<String, Object> paramSearch = new LinkedMultiValueMap<>();
//        paramSearch.add("key",key);
//        paramSearch.add("sid",riderSid);
//        String[] split = point.split(",");
//        BigDecimal s1 = new BigDecimal(split[1]).setScale(6, RoundingMode.HALF_UP);
//        BigDecimal s0= new BigDecimal(split[0]).setScale(6,RoundingMode.HALF_UP);
//        point=s1.doubleValue()+","+s0.doubleValue();
//
//        paramSearch.add("center",point);
//        //最大半径5000米
//        int radius= taskDecimal.compareTo(new BigDecimal(5))>=0?5000:taskDecimal.multiply(new BigDecimal(1000)).setScale(0, RoundingMode.HALF_UP).intValue();
//        paramSearch.add("radius",radius+"");
//        Map<String, Object> responseMessageSearch = requestGould(paramSearch, aroundsearch==null?"https://tsapi.amap.com/v1/track/terminal/aroundsearch":aroundsearch);
//        if (Integer.valueOf(responseMessageSearch.get("errcode").toString()).intValue()!=10000){
//            throw new RuntimeException("查找附近终端错误:"+responseMessageSearch.get("errdetail").toString());
//        }
//
//        List<Map<String,Object>> result = (List<Map<String,Object>>)(((Map) responseMessageSearch.get("data")).get("results"));
//        log.info("搜索返回查看"+JSONUtils.toJSONString(result));
//        if (result!=null && result.size() > 0){
//            List<String> cids=new ArrayList<>();
//            for (Map<String,Object> map:
//                    result) {
//                String userMapJsonStr = redisUtils.get("rider_" + map.get("name").toString());
//                //接单标识
//                String flag = redisUtils.get("rider_receipt_flag_" + map.get("name"));
//                log.info("缓存查看"+userMapJsonStr);
//                if (StringUtils.isNotBlank(userMapJsonStr)) {
//                    Map userMap = (Map) JSONUtils.parse(userMapJsonStr);
//                    if (userMap.get("cid")!=null && StringUtils.isNotBlank(flag)){
//                        cids.add(userMap.get("cid").toString());
//                    }
//                }
//            }
//            Map<String,String> message=new HashMap<>();
//            message.put("title", "GG众包任务提醒");
//            message.put("titleText", "你的附近有新的任务,请及时查看");
//            message.put("transText", "");
//            if (cids.size()>0){
//                log.info(appPush.toString());
//                //发送推送给附近骑手
//                IPushResult iPushResult = appPush.pushMsgToManyByAppPacket(cids, message,riderAppKey,riderMasterSecret,riderAppId,riderPacket);
//                log.info("骑手推送日志记录"+JSONUtils.toJSONString(iPushResult.getResponse()));
//            }
//        }
//
//        redisUtils.set("order_tid_"+order.getId(),tid);
//        redisUtils.set("order_trid_"+order.getId(),((Map)responseMessageTrack.get("data")).get("trid").toString());
    }
    //生成轨迹点
    private void createTrackPoint(List points,String tid, String trid,String taskId) throws Exception {
        Thread.sleep(100);
        log.info("tid:"+tid+",trid:"+trid+",taskId:"+taskId);
        MultiValueMap<String, Object> paramTrackPoint = new LinkedMultiValueMap<>();
        paramTrackPoint.add("key",key);
        paramTrackPoint.add("sid",taskSid);
        paramTrackPoint.add("tid",tid);
        paramTrackPoint.add("trid",trid);
        paramTrackPoint.add("points", JSONUtils.toJSONString(points));

        Map<String, Object> responseMessageTrackPoint = requestGould(paramTrackPoint, tracePointUpload);
        log.info("生成轨迹点："+JSONUtils.toJSONString(responseMessageTrackPoint));
        if (Integer.valueOf(responseMessageTrackPoint.get("errcode").toString()).intValue()!=10000){
            throw new RuntimeException("轨迹点生成错误:"+responseMessageTrackPoint.get("errdetail").toString());
        }
        if (bindMap.get("orderId")==null){
            bindMap.put("orderId",0);
        }

        if (Integer.valueOf(bindMap.get("orderId").toString()).intValue()<5 ) {
            //监测
            checkLocusPoint(taskId, tid, trid, points);
            bindMap.remove("orderId");
            return;
        }else{
            bindMap.remove("orderId");
            throw new RuntimeException("轨迹点创建失败");
        }

    }

    //监测轨迹点是否存在 不存在则重新生成
    private void checkLocusPoint(String taskId,String tid,String trid,List points) throws Exception{
        Thread.sleep(100);
        MultiValueMap<String, Object> paramCheckPoint = new LinkedMultiValueMap<>();
        paramCheckPoint.add("key",key);
        paramCheckPoint.add("sid",taskSid);
        paramCheckPoint.add("keywords",taskId+"");

        Map<String, Object> responseMessageTrackPoint = requestGould(paramCheckPoint, search);
        log.info("查看轨迹点："+JSONUtils.toJSONString(responseMessageTrackPoint));
        if (Integer.valueOf(responseMessageTrackPoint.get("errcode").toString()).intValue()!=10000){
            throw new RuntimeException("轨迹点生成错误:"+responseMessageTrackPoint.get("errdetail").toString());
        }
        List<Map<String,Object>> result = (List<Map<String,Object>>)(((Map) responseMessageTrackPoint.get("data")).get("results"));
        if (result==null|| result.size()<=0){
            bindMap.put("orderId",Integer.valueOf(bindMap.get("orderId").toString()).intValue()+1);
            //为空重新生成
            createTrackPoint(points,tid,trid,taskId);
            return;
        }

        if ( result.get(0).get("location")==null){
            bindMap.put("orderId",Integer.valueOf(bindMap.get("orderId")==null?"0":bindMap.get("orderId").toString()).intValue()+1);
            //为空重新生成
            createTrackPoint(points,tid,trid,taskId);
            return;
        }

    }


    public String createUserClient(User user)  throws  Exception {
        //创建用户终端
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("key",key);
        param.add("sid",userSid);
        param.add("name",user.getUserId()+"");
        param.add("desc","用户"+user.getUserName());
        Map<String, Object> responseMessage = requestGould(param, addTerminalUrl);
        if (Integer.valueOf(responseMessage.get("errcode").toString()).intValue()!=10000){
            throw new RuntimeException("终端生成错误:"+responseMessage.get("errdetail").toString());
        }

        return ((Map)responseMessage.get("data")).get("tid").toString();
    }


    public String delRiderClient(String tid)  throws  Exception{

//        String userMapJsonStr = redisUtils.get("rider_" + eUserRider.getUserId());
//        if (StringUtils.isNotBlank(userMapJsonStr)){
//            Map userMap = (Map)JSONUtils.parse(userMapJsonStr);
//            //删除骑手终端
//            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
//            param.add("key",key);
//            param.add("sid",riderSid);
//            param.add("tid",tid);
//            Map<String, Object> responseMessage = requestGould(param, delTerminalUrl);
//            if (Integer.valueOf(responseMessage.get("errcode").toString()).intValue()!=10000){
//                throw new RuntimeException("终端删除错误:"+responseMessage.get("errdetail").toString());
//            }
//
//            //设置终端
//            userMap.put("sid",riderSid);
//            userMap.put("tid","");
//            redisUtils.set("rider_" + eUserRider.getUserId(),JSONUtils.toJSONString(userMap));
//        }
//
//
//        return "成功";
        return null;
    }


    public String delTaskClient(String tid) {

        //删除任务终端
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("key",key);
        param.add("sid",taskSid);
        param.add("tid",tid);
        Map<String, Object> responseMessage = requestGould(param, delTerminalUrl);
        if (Integer.valueOf(responseMessage.get("errcode").toString()).intValue()!=10000){
            log.error("终端删除错误:"+responseMessage.get("errdetail").toString());
        }

        return "成功";
    }


    public String delTaskTrackClient(String tid,String trid)  {
        //删除任务轨迹
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("key",key);
        param.add("sid",taskSid);
        param.add("tid",tid);
        param.add("trid",trid);
        Map<String, Object> responseMessage = requestGould(param, delTraceTerminalUrl);
        if (Integer.valueOf(responseMessage.get("errcode").toString()).intValue()!=10000){
            log.error("轨迹删除错误:"+responseMessage.get("errdetail").toString());
        }

        return "成功";
    }


    private Map<String, Object> requestGould(MultiValueMap<String, Object> paramTrackPoint, String url) {
        HttpHeaders headersTrackPoint = new HttpHeaders();
        headersTrackPoint.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity<MultiValueMap<String, Object>> rTrackPoint = new HttpEntity<>(paramTrackPoint, headersTrackPoint);
        return restTemplate.postForObject(url, rTrackPoint, Map.class);
    }
}
